import { BuildOptions, defineConfig } from 'vite'
import progress from 'vite-plugin-progress'
import { vite as emt, render } from 'unplugin-emt-styl'
import { vite as styl, compileStylusInHtml } from 'unplugin-emt-styl/styl'
import { ViteMinifyPlugin as minify } from 'vite-plugin-minify'
import UnoCSS from 'unocss/postcss'
import { globSync } from 'node:fs'

export default defineConfig(({ mode }) => {
	const dev = mode == 'development'
	const build: BuildOptions = {
		assetsDir: '.',
		outDir: '../ui',
		emptyOutDir: true,
		modulePreload: false,
		sourcemap: dev && 'hidden',
		target: 'esnext',
		rollupOptions: {
			input: globSync('views/*.html'),
		}
	}
	if (!dev) {
		build.minify = 'terser'
		build.terserOptions = {
			ecma: 2020,
			compress: {
				ecma: 2020,
				unsafe: true
			}
		}
	}
	const plugins = [
		emt({
			paths: ['tpl'],
			render: (str, data, maxDepth) => {
				data.textInput = 'input input-bordered input-sm'
				return compileStylusInHtml()(render(str, data, maxDepth).replace(/\.emt/g, ".html"))
			},
			root: 'views',
		}),
		styl(),
		progress({
			srcDir: 'views',
		})
	]
	if (!dev)
		plugins.push(minify({
			removeAttributeQuotes: true
		}))
	return {
		root: 'views',
		build,
		css: {
			postcss: {
				plugins: [UnoCSS()]
			}
		},
		optimizeDeps: {
			include: ['@ygoe/msgpack'],
			esbuildOptions: {
				target: 'esnext'
			}
		},
		plugins,
	}
})